package utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class StringUtils {

	/**
	 * Return the String with the first letter uppercase. Useful for class name.
	 */
	public static String firstUpper(String s) {
		if (s.length() > 0) {
			s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
		}
		return s;
	}

	/**
	 * Return the String with the first letter lowercase. Useful for attribute
	 * name.
	 */
	public static String firstLower(String s) {
		if (s.length() > 0) {
			s = Character.toLowerCase(s.charAt(0)) + s.substring(1);
		}
		return s;
	}

	/**
	 * Transform a String with notation aa.bb.cc to aa/bb/cc<br/>
	 * Usefull for package translating.
	 */
	public static String toPath(String packageName) {
		return packageName.trim().replaceAll("\\.", "/");
	}

	/**
	 * Transform a String to the String representation in java code.
	 * 
	 * @param str
	 * @return
	 */
	public static String stringToCode(String str) {
		StringBuilder sb = new StringBuilder(str);
		StringBuilder ret = new StringBuilder();
		char c;
		for (int i = 0; i < sb.length(); i++) {
			c = sb.charAt(i);
			String s;
			switch (c) {
			case '\n':
				s = "\\n";
				break;
			case '\b':
				s = "\\b";
				break;
			case '\r':
				s = "\\r";
				break;
			case '\f':
				s = "\\f";
				break;
			case '\t':
				s = "\\t";
				break;
			case '\'':
				s = "\\\'";
				break;
			case '\"':
				s = "\\\"";
				break;
			case '\\':
				s = "\\";
				break;
			default:
				s = c + "";
			}
			ret.append(s);
		}
		return ret.toString();
	}

	/**
	 * Transform a string in a byte array.
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] toBytes(String str) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(baos);
		try {
			osw.write(str);
			osw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return baos.toByteArray();
	}

	public static String templateNameToClassName(String templateName) {
		StringBuilder sb = new StringBuilder();
		boolean begin = true;
		for (int i = 0; i < templateName.length(); i++) {
			char c = templateName.charAt(i);
			if (c == '.' || c == '_') {
				begin = true;
			} else {
				if (begin) {
					c = Character.toUpperCase(c);
					begin = false;
				}
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public static boolean isMethod(String name) {
		return (name != null && name.trim().length() > 0 && name.indexOf('(') != -1);
	}

}
